﻿using System;
using System.Collections.Generic;
using System.Text;
using Telerik.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Acms.WebControls
{
    public class RadGridRadioButtonColumn : GridBoundColumn
    {
        public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem)
        {
            if (inItem is GridDataItem)
            {
                RadioButton ctrl = new RadioButton();
                ctrl.ID = string.Format("radioButton_{0}_{1}", this.UniqueName, inItem.ItemIndex);
                ctrl.Enabled = inItem.IsInEditMode;
                ctrl.GroupName = string.Concat(Owner.UniqueID, "$", columnIndex);
                cell.Controls.Add(ctrl);
                cell.DataBinding += new EventHandler(cell_DataBinding);

            }
            else
            {
                base.InitializeCell(cell, columnIndex, inItem);
            }
        }

        void cell_DataBinding(object sender, EventArgs e)
        {
            TableCell cell = sender as TableCell;
            if (cell != null)
            {
                RadioButton ctrl = cell.Controls[0] as RadioButton;
                object dataItem = DataBinder.GetDataItem(ctrl.NamingContainer);
                if (dataItem != null)
                {
                    object val = DataBinder.Eval(dataItem, DataField);
                    bool isChecked = false;
                    if (val is bool)
                    {
                        isChecked = (bool)val;
                    }
                    else if (val != null)
                    {
                        try
                        {
                            isChecked = bool.Parse(val.ToString());
                        }
                        catch
                        {
                        }
                    }
                    ctrl.Checked = isChecked;
                }
            }
        }

        public override void FillValues(System.Collections.IDictionary newValues, GridEditableItem editableItem)
        {
            RadioButton ctrl = editableItem.FindControl(string.Format("radioButton_{0}_{1}", this.UniqueName, editableItem.ItemIndex)) as RadioButton;
            if (ctrl != null)
            {
                newValues[this.DataField] = ctrl.Checked;
            }
        }
    }
}
